import React, {useEffect, useState} from 'react'
import { Form, Button,Input, Modal, Row, Col,DatePicker,Switch,Upload,message,Select} from 'antd'
import { connect } from 'umi'
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from "@/utils/upload";
import {bulletinTypeList} from "@/utils/constant";
import moment from 'moment';
const FormItem = Form.Item
const { TextArea } = Input;
const {Option} = Select

const formLayout = {
  labelCol: { span: 7 },
}

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
}

let uploadedFiles = [];

const AddForm = (props) => {
  const { onSubmit, onCancel,typeValue,loading,record,visible} = props
  const [form] = Form.useForm()
  const [fileUploadUrls,setFileUploadUrls] = useState([])
  const [fileName, setFileName] = useState(null)
  const [title,setTitle] = useState(null)
  const titleType = typeValue === 1?'系统公告':'公司公告'

  useEffect(() => {
    if(record && visible){
      setTitle(`编辑` + titleType);
      form.setFieldsValue({...record,time:record.time ? moment(record.time) : undefined,urlIds:record.fileUrlList && record.fileUrlList.toString()});
      setFileUploadUrls(record.fileUrlList);
      record.fileUrlList.forEach((item,index) =>{
        uploadedFiles.push({
          key:index,
          uid: index,
          name: item.split('----')[1],
          status: 'done',
          url: item,
        })
      })
    }else{
      form.resetFields();
      setTitle(`新增` + titleType)
      form.setFieldsValue({type:typeValue,time:moment()})
    }
  }, [visible])

  const onFormCancel = () => {
    setFileUploadUrls([])
    form.resetFields()
    onCancel()
    uploadedFiles = [];
  }

  const disabledDate = (current) => {
    return current && current < moment().endOf('day');
  }

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({
      ...fieldsValue,
      fileUrlList:fileUploadUrls,
      isNew:fieldsValue.isNew?1:0,
      id:record && record.id
    });
    setFileUploadUrls([]);
    uploadedFiles = [];
  };

  const fileList = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    defaultFileList: uploadedFiles,
    data: {name: fileName},
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="title" label="公告标题" rules={[{required: true, message: '公告标题不能为空'}]}>
             <Input placeholder="请输入公告标题"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="subtitle" label="公告副标题">
              <Input placeholder="请输入公告副标题"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="type" label="公告类型">
              <Select placeholder="请选择公告类型" disabled={true}>
                {bulletinTypeList.map((item, index) => {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem label="公告内容" name="content" labelCol={{span: 2}} rules={[{required: true, message: '公告内容不能为空'}]}>
              <TextArea placeholder="请输入公告内容" rows={4} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="urlIds" label="上传附件">
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="time" label="发布时间">
              <DatePicker placeholder="请选择发布时间" disabledDate={disabledDate} showTime={{ format: 'HH:mm' }} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="isNew" label="是否新公告">
              <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked={record && record.isNew === 1 ?true:false}/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" loading={loading} onClick={() => handleSubmit()}>提交</Button>
      </>
    )
  }

  return (
    <Modal
      width={1280}
      destroyOnClose
      title={title}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(() => ({
}))(AddForm)
